import 'dart:async';
import 'dart:ffi';
import 'dart:io';

import 'package:app_document/app_document.dart';
import 'package:crypto/crypto.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:path/path.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _platformVersion = 'Unknown';
  final _appDocumentPlugin = AppDocument();

  @override
  void initState() {
    super.initState();
    initPlatformState();
  }

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initPlatformState() async {
    String platformVersion;
    // Platform messages may fail, so we use a try/catch PlatformException.
    // We also handle the message potentially returning null.
    try {
      platformVersion = await _appDocumentPlugin.getDocumentPath() ??
          'Unknown platform version';
    } on PlatformException {
      platformVersion = 'Failed to get platform version.';
    }

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;

    setState(() {
      _platformVersion = platformVersion;
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Center(
          child: Column(
            children: [
              Text('Path: $_platformVersion\n'),
              const SizedBox(
                height: 80,
              ),
              GestureDetector(
                onTap: () {
                  openSqlite();
                },
                child: Container(
                  alignment: Alignment.center,
                  height: 50,
                  width: 200,
                  color: Colors.lightBlue,
                  child: const Text(
                    '打开sqlite.so文件',
                    style: TextStyle(color: Colors.white),
                  ),
                ),
              )
            ],
          ),
        ),
      ),
    );
  }

  Future<DynamicLibrary?> openSqlite() async {
    // 从 assets 中读取文件内容
    final fileBytes = await rootBundle.load('assets/libsqlite3.so');
    final dirPath = await _appDocumentPlugin.getDocumentPath();
    String filePath = join(dirPath!, 'libsqlite3.so');
    filePath = filePath.replaceFirst('/documents', '');
    final originalFileBytes = fileBytes.buffer.asUint8List();

    final originalMd5 = md5.convert(originalFileBytes).toString();
    print('Original file MD5: $originalMd5');
    // 检查文件是否存在
    final file = File(filePath);
    if (await file.exists()) {
      // 如果文件存在,则删除它
      await file.delete();
    }
    // 将文件写入文档目录
    try {
      await file.writeAsBytes(fileBytes.buffer.asUint8List());
      // 5. 读取写入后的文件,计算 MD5 值并进行对比
      final writtenFileBytes = await file.readAsBytes();
      final writtenMd5 = md5.convert(writtenFileBytes).toString();
      print('Written file MD5: $writtenMd5');
    } catch (e) {
      print('文件写入错误:$e');
      rethrow;
    }

    if (await file.exists()) {
      print('文件已写入,准备读取');
    } else {
      print('文件没有写入');
    }
    try {
      final a = DynamicLibrary.open(filePath);
      print('加载so库成功');
      return a;
    } catch (e) {
      print('加载so库失败。errorInfo：$e');
    }
    return null;
  }
}
